<template>
  <div class="customer-list-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入企业名称/客户名称/手机号"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
        <el-button type="primary" size="small" style="margin-left: 20px;" @click="handleAdd">新增客户</el-button>
      </div>
    </div>

    <!-- 客户列表表格 -->
    <el-table 
      :data="customerList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      
      <el-table-column prop="Name" label="企业名称" min-width="200px"></el-table-column>
      <el-table-column prop="UserName" label="负责人姓名" width="120px"></el-table-column>
      <el-table-column prop="UserTel" label="负责人电话" width="130px"></el-table-column>
      <el-table-column prop="Tel" label="联系电话" width="130px"></el-table-column>
      <el-table-column prop="Type" label="企业分类" width="120px"></el-table-column>
      <el-table-column prop="Scale" label="产废规模" width="120px"></el-table-column>
      <el-table-column prop="Address" label="企业地址" min-width="200px" show-overflow-tooltip></el-table-column>
      <el-table-column prop="State" label="状态" width="120px" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStateInfo(scope.row.State).type">
            {{ getStateInfo(scope.row.State).text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="AddTime" label="添加时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.AddTime) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="LastTime" label="最后沟通时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.LastTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="VisitCount" label="沟通次数" width="100px" align="center"></el-table-column> -->
             <el-table-column label="操作" width="180px" align="center"  fixed="right">
         <template slot-scope="scope">
           <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
           <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
         </template>
       </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 客户详情弹窗 -->
    <el-dialog
      title="客户详情"
      :visible.sync="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="detailLoading">
        <el-descriptions :column="2" border>
          <!-- <el-descriptions-item label="客户ID">{{ customerDetail.CustomerId || '-' }}</el-descriptions-item> -->
          <el-descriptions-item label="状态">
            <el-tag :type="customerDetail.State === 1 ? 'success' : 'danger'">
              {{ customerDetail.State === 1 ? '正常' : '异常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="企业名称">{{ customerDetail.Name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="信用代码">{{ customerDetail.LicenseNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="企业地址" :span="2">{{ customerDetail.Address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ customerDetail.Tel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="其他电话">{{ customerDetail.OtherTel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="负责人姓名">{{ customerDetail.UserName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="负责人电话">{{ customerDetail.UserTel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="企业分类">{{ customerDetail.Type || '-' }}</el-descriptions-item>
          <el-descriptions-item label="产废规模">{{ customerDetail.Scale || '-' }}</el-descriptions-item>
          <el-descriptions-item label="客户来源">{{ customerDetail.Source || '-' }}</el-descriptions-item>
          <el-descriptions-item label="是否接入平台">
            <el-tag :type="customerDetail.isPlanform === 1 ? 'success' : 'info'">
              {{ customerDetail.isPlanform === 1 ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否为代理商">
            <el-tag :type="customerDetail.IsAgent === 1 ? 'warning' : 'info'">
              {{ customerDetail.IsAgent === 1 ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="添加时间">{{ formatDateTime(customerDetail.AddTime) }}</el-descriptions-item>
          <el-descriptions-item label="绑定时间">{{ formatDateTime(customerDetail.BindTime) }}</el-descriptions-item>
          <el-descriptions-item label="合计沟通次数">{{ customerDetail.VisitCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ customerDetail.Note || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 合同信息展示 -->
        <div class="contract-info-section" v-if="customerDetail.contractData && customerDetail.contractData.length > 0">
          <h3 class="section-title">合同信息</h3>
          <el-table :data="customerDetail.contractData" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="contract_name" label="合同编号" width="180px"></el-table-column>
            <el-table-column label="创建时间" width="160px" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column label="付款时间" width="160px" align="center">
              <template slot-scope="scope">
                {{ scope.row.payment_time ? formatDateTime(scope.row.payment_time) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="付款状态" width="100px" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.payment_status === 1 ? 'success' : 'warning'">
                  {{ scope.row.payment_status === 1 ? '已付款' : '未付款' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="施工状态" width="100px" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.is_construction === 1 ? 'success' : 'info'">
                  {{ scope.row.is_construction === 1 ? '施工' : '不施工' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="合同凭证" width="100px" align="center">
              <template slot-scope="scope">
                <el-button 
                  v-if="scope.row.img_url" 
                  type="text" 
                  size="small" 
                  @click="handleViewContractImages(scope.row.img_url)"
                >
                  查看凭证
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="付款凭证" width="100px" align="center">
              <template slot-scope="scope">
                <el-button 
                  v-if="scope.row.evidence_payment" 
                  type="text" 
                  size="small" 
                  @click="handleViewPaymentImages(scope.row.evidence_payment)"
                >
                  查看凭证
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="no-contract-info">
          <p>暂无合同信息</p>
        </div>
      </div>
             <div slot="footer" class="dialog-footer">
         <el-button @click="detailDialogVisible = false">关 闭</el-button>
                </div>
       </el-dialog>

       <!-- 合同图片预览弹窗 -->
       <el-dialog
         title="合同凭证图片预览"
         :visible.sync="contractImageDialogVisible"
         width="800px"
         :close-on-click-modal="false"
         center
       >
         <div class="image-preview-container">
           <el-image 
             v-for="(url, idx) in currentContractImageUrls"
             :key="url"
             :src="url"
             style="width: 100%; max-height: 500px; margin-bottom: 10px;"
             fit="contain"
             :preview-src-list="currentContractImageUrls"
             :initial-index="idx"
             lazy
           >
             <div slot="placeholder" class="image-slot">
               <i class="el-icon-loading"></i>
               <p>图片加载中...</p>
             </div>
             <div slot="error" class="image-slot">
               <i class="el-icon-picture-outline"></i>
               <p>图片加载失败</p>
             </div>
           </el-image>
         </div>
         <div slot="footer" class="dialog-footer">
           <el-button @click="contractImageDialogVisible = false">关 闭</el-button>
         </div>
       </el-dialog>

       <!-- 付款凭证图片预览弹窗 -->
       <el-dialog
         title="付款凭证图片预览"
         :visible.sync="paymentImageDialogVisible"
         width="800px"
         :close-on-click-modal="false"
         center
       >
         <div class="image-preview-container">
           <el-image 
             v-for="(url, idx) in currentPaymentImageUrls"
             :key="url"
             :src="url"
             style="width: 100%; max-height: 500px; margin-bottom: 10px;"
             fit="contain"
             :preview-src-list="currentPaymentImageUrls"
             :initial-index="idx"
             lazy
           >
             <div slot="placeholder" class="image-slot">
               <i class="el-icon-loading"></i>
               <p>图片加载中...</p>
             </div>
             <div slot="error" class="image-slot">
               <i class="el-icon-picture-outline"></i>
               <p>图片加载失败</p>
             </div>
           </el-image>
         </div>
         <div slot="footer" class="dialog-footer">
           <el-button @click="paymentImageDialogVisible = false">关 闭</el-button>
         </div>
       </el-dialog>

     <!-- 编辑客户弹窗 -->
     <el-dialog
       title="编辑客户信息"
       :visible.sync="editDialogVisible"
       width="800px"
       :close-on-click-modal="false"
       @close="resetEditForm"
     >
       <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
         <el-row :gutter="20">
           <!-- <el-col :span="12">
             <el-form-item label="客户ID" prop="CustomerId">
               <el-input v-model="editForm.CustomerId" disabled></el-input>
             </el-form-item>
           </el-col> -->
              <el-col :span="12">
              <el-form-item label="企业名称">
                <el-input v-model="editForm.Name" placeholder="请输入企业名称"></el-input>
              </el-form-item>
            </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="联系电话">
               <el-input v-model="editForm.Tel" placeholder="请输入联系电话"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="其他电话">
               <el-input v-model="editForm.OtherTel" placeholder="请输入其他电话"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="负责人姓名">
               <el-input v-model="editForm.UserName" placeholder="请输入负责人姓名"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="负责人电话">
               <el-input v-model="editForm.UserTel" placeholder="请输入负责人电话"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="企业分类">
               <el-input v-model="editForm.Type" placeholder="请输入企业分类"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="产废规模">
               <el-input v-model="editForm.Scale" placeholder="请输入产废规模"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="信用代码">
               <el-input v-model="editForm.LicenseNumber" placeholder="请输入信用代码"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="客户来源">
               <el-input v-model="editForm.Source" placeholder="请输入客户来源"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="是否接入平台">
               <el-radio-group v-model="editForm.isPlanform">
                 <el-radio :label="1">是</el-radio>
                 <el-radio :label="0">否</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="是否为代理商">
               <el-radio-group v-model="editForm.IsAgent">
                 <el-radio :label="1">是</el-radio>
                 <el-radio :label="0">否</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-form-item label="企业地址">
           <el-input v-model="editForm.Address" placeholder="请输入企业地址"></el-input>
         </el-form-item>
         
         <el-form-item label="备注">
           <el-input
             type="textarea"
             v-model="editForm.Note"
             placeholder="请输入备注信息"
             :rows="3"
           ></el-input>
         </el-form-item>
       </el-form>
       
       <div slot="footer" class="dialog-footer">
         <el-button @click="editDialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="submitEditForm" :loading="submitLoading">确 定</el-button>
       </div>
     </el-dialog>

     <!-- 新增客户弹窗 -->
     <el-dialog
       title="新增客户"
       :visible.sync="addDialogVisible"
       width="800px"
       :close-on-click-modal="false"
       @close="resetAddForm"
     >
       <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="120px">
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="企业名称" prop="Name">
               <el-input v-model="addForm.Name" placeholder="请输入企业名称"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="信用代码" prop="LicenseNumber">
               <el-input v-model="addForm.LicenseNumber" placeholder="请输入信用代码"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="联系电话" prop="Tel">
               <el-input v-model="addForm.Tel" placeholder="请输入联系电话"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="其他电话" prop="OtherTel">
               <el-input v-model="addForm.OtherTel" placeholder="请输入其他电话"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="负责人姓名" prop="UserName">
               <el-input v-model="addForm.UserName" placeholder="请输入负责人姓名"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="负责人电话" prop="UserTel">
               <el-input v-model="addForm.UserTel" placeholder="请输入负责人电话"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="企业分类" prop="Type">
               <el-input v-model="addForm.Type" placeholder="请输入企业分类"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="产废规模" prop="Scale">
               <el-input v-model="addForm.Scale" placeholder="请输入产废规模"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="客户来源" prop="Source">
               <el-input v-model="addForm.Source" placeholder="请输入客户来源"></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-form-item label="企业地址" prop="Address">
           <el-input v-model="addForm.Address" placeholder="请输入企业地址"></el-input>
         </el-form-item>
         
         <el-form-item label="备注" prop="Note">
           <el-input
             type="textarea"
             v-model="addForm.Note"
             placeholder="请输入备注信息"
             :rows="3"
           ></el-input>
         </el-form-item>
       </el-form>
       
       <div slot="footer" class="dialog-footer">
         <el-button @click="addDialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="submitAddForm" :loading="addSubmitLoading">确 定</el-button>
       </div>
     </el-dialog>
   </div>
 </template>

<script>
import { getCustomerList, getCustomerDetail, editCustomer, addCustomer } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'CustomerManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 列表相关
      customerList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
             // 详情弹窗相关
       detailDialogVisible: false,
       detailLoading: false,
       customerDetail: {},
       
       // 图片预览弹窗相关
       contractImageDialogVisible: false,
       paymentImageDialogVisible: false,
       currentContractImageUrls: [],
       currentPaymentImageUrls: [],
       

       
       // 编辑弹窗相关
       editDialogVisible: false,
       submitLoading: false,
       editForm: {
         CustomerId: '',
         Name: '',
         Address: '',
         Tel: '',
         OtherTel: '',
         UserName: '',
         UserTel: '',
         Type: '',
         Scale: '',
         Note: '',
         Source: '',
         LicenseNumber: '',
         isPlanform: 0,
         IsAgent: 0
       },
       editRules: {},
       
       // 新增客户弹窗相关
       addDialogVisible: false,
       addSubmitLoading: false,
       addForm: {
         Name: '',
         Address: '',
         Tel: '',
         OtherTel: '',
         UserName: '',
         UserTel: '',
         Type: '',
         Scale: '',
         Note: '',
         LicenseNumber: '',
         Source: ''
       },
       addRules: {
         Name: [
           { required: true, message: '请输入企业名称', trigger: 'blur' }
         ],
         Address: [
           { required: true, message: '请输入企业地址', trigger: 'blur' }
         ],
         Tel: [
           { required: true, message: '请输入联系电话', trigger: 'blur' }
         ],
         UserName: [
           { required: true, message: '请输入负责人姓名', trigger: 'blur' }
         ]
       }
    }
  },
  mounted() {
    this.fetchCustomerList();
  },
  methods: {
    //客户状态映射
   getStateInfo(state) {
    const stateMap = {
      1: { text: "目标客户", type: "info" },
      2: { text: "跟进中", type: "primary" },
      3: { text: "一般客户", type: "warning" },
      11: { text: "重点目标客户", type: "success" },
      12: { text: "重点跟进", type: "success" },
      99: { text: "已成交", type: "success" },
      404: { text: "无效", type: "danger" },
      "-1": { text: "全部客户", type: "default" }
    };
    
    // 默认值处理
    return stateMap[state] || { text: "未知状态", type: "default" };
  },
    // 获取客户列表
    async fetchCustomerList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }
        
        const response = await getCustomerList(params);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.customerList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取客户列表失败');
        }
      } catch (error) {
        console.error('获取客户列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取客户列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchCustomerList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchCustomerList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchCustomerList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchCustomerList();
    },
    
    // 查看详情
    async handleViewDetail(row) {
      this.detailDialogVisible = true;
      this.detailLoading = true;
      this.customerDetail = {};
      
      try {
        const response = await getCustomerDetail(row.CustomerId);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.customerDetail = response.data.data || {};
        } else {
          this.$message.error(response.data.msg || '获取客户详情失败');
        }
      } catch (error) {
        console.error('获取客户详情失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取客户详情失败');
        }
      } finally {
        this.detailLoading = false;
      }
    },
    
         // 格式化日期时间
     formatDateTime(dateTime) {
       if (!dateTime) return '-';
       
       // 如果是时间戳（数字），需要转换为毫秒
       let date;
       if (typeof dateTime === 'number') {
         // 如果时间戳是秒级的，转换为毫秒
         if (dateTime < 10000000000) {
           date = new Date(dateTime * 1000);
         } else {
           date = new Date(dateTime);
         }
       } else {
         date = new Date(dateTime);
       }
       
       return date.toLocaleString('zh-CN', {
         year: 'numeric',
         month: '2-digit',
         day: '2-digit',
         hour: '2-digit',
         minute: '2-digit',
         second: '2-digit'
       });
     },
     
     // 编辑客户
     async handleEdit(row) {
       // 先获取客户详情数据
       this.detailLoading = true;
       try {
         const response = await getCustomerDetail(row.CustomerId);
         
         if (response.data && response.data.code) {
           // API成功返回数据
           const customerDetail = response.data.data || {};
           
                       // 将详情数据复制到编辑表单，处理null值
            this.editForm = {
              CustomerId: customerDetail.CustomerId || '',
              Name: customerDetail.Name || '',
              Address: customerDetail.Address || '',
              Tel: customerDetail.Tel || '',
              OtherTel: customerDetail.OtherTel || '',
              UserName: customerDetail.UserName || '',
              UserTel: customerDetail.UserTel || '',
              Type: customerDetail.Type || '',
              Scale: customerDetail.Scale || '',
              Note: customerDetail.Note || '',
              Source: customerDetail.Source || '',
              LicenseNumber: customerDetail.LicenseNumber || '',
              isPlanform: customerDetail.isPlanform || 0,
              IsAgent: customerDetail.IsAgent || 0
            };
            
            // 处理null值，将null转换为空字符串
            Object.keys(this.editForm).forEach(key => {
              if (this.editForm[key] === null || this.editForm[key] === undefined) {
                this.editForm[key] = '';
              }
            });
           
           this.editDialogVisible = true;
         } else {
           this.$message.error(response.data.msg || '获取客户详情失败');
         }
       } catch (error) {
         console.error('获取客户详情失败:', error);
         if (checkTokenFromError(error)) {
           // Token无效或过期
           this.$message.error('登录已过期，请重新登录');
           handleTokenExpired();
         } else {
           // 其他错误
           this.$message.error('获取客户详情失败');
         }
       } finally {
         this.detailLoading = false;
       }
     },
     
           // 提交编辑表单
      async submitEditForm() {
        this.submitLoading = true;
        try {
          // 检查token是否存在
          if (!checkToken()) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
            return;
          }
          
          // 处理空字符串，将空字符串转换为null或undefined
          const submitData = { ...this.editForm };
          
          // 处理其他可能为空的字段
          Object.keys(submitData).forEach(key => {
            if (submitData[key] === '') {
              submitData[key] = null;
            }
          });
          
          const response = await editCustomer(submitData);
          
                       if (response.data && response.data.code === 1) {
                this.$message.success('客户信息修改成功');
                this.editDialogVisible = false;
                // 重新获取客户列表
                this.fetchCustomerList();
              } else {
            this.$message.error(response.data.msg || '客户信息修改失败');
          }
        } catch (error) {
          console.error('修改客户信息失败:', error);
          if (checkTokenFromError(error)) {
            // Token无效或过期
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            // 其他错误
            this.$message.error('修改客户信息失败');
          }
        } finally {
          this.submitLoading = false;
        }
      },
     
     // 重置编辑表单
     resetEditForm() {
       this.$refs.editForm && this.$refs.editForm.resetFields();
       this.editForm = {
         CustomerId: '',
         Name: '',
         Address: '',
         Tel: '',
         OtherTel: '',
         UserName: '',
         UserTel: '',
         Type: '',
         Scale: '',
         Note: '',
         Source: '',
         LicenseNumber: '',
         isPlanform: 0,
         IsAgent: 0
       };
     },
     
     // 新增客户
     handleAdd() {
       this.addDialogVisible = true;
     },
     
     // 提交新增表单
     async submitAddForm() {
       try {
         // 检查token是否存在
         if (!checkToken()) {
           this.$message.error('登录已过期，请重新登录');
           handleTokenExpired();
           return;
         }
         
         // 验证表单
         const valid = await this.$refs.addForm.validate();
         if (!valid) {
           return;
         }
         
         this.addSubmitLoading = true;
         
         // 准备提交数据
         const submitData = { ...this.addForm };
         
         // 处理其他可能为空的字段
         Object.keys(submitData).forEach(key => {
           if (submitData[key] === '') {
             submitData[key] = null;
           }
         });
         
         const response = await addCustomer(submitData);
         
         if (response.data && response.data.code === 1) {
           this.$message.success('客户添加成功');
           this.addDialogVisible = false;
           // 重新获取客户列表
           this.fetchCustomerList();
         } else {
           this.$message.error(response.data.msg || '客户添加失败');
         }
       } catch (error) {
         console.error('添加客户失败:', error);
         if (checkTokenFromError(error)) {
           // Token无效或过期
           this.$message.error('登录已过期，请重新登录');
           handleTokenExpired();
         } else {
           // 其他错误
           this.$message.error('添加客户失败');
         }
       } finally {
         this.addSubmitLoading = false;
       }
     },
     
     // 重置新增表单
     resetAddForm() {
       this.$refs.addForm && this.$refs.addForm.resetFields();
       this.addForm = {
         Name: '',
         Address: '',
         Tel: '',
         OtherTel: '',
         UserName: '',
         UserTel: '',
         Type: '',
         Scale: '',
         Note: '',
         LicenseNumber: '',
         Source: ''
       };
     },
     
     // 查看合同凭证图片
     handleViewContractImages(imgUrl) {
       if (imgUrl) {
         this.currentContractImageUrls = imgUrl.split(',').filter(Boolean);
         this.contractImageDialogVisible = true;
       }
     },
     
     // 查看付款凭证图片
     handleViewPaymentImages(evidencePayment) {
       if (evidencePayment) {
         this.currentPaymentImageUrls = evidencePayment.split(',').filter(Boolean);
         this.paymentImageDialogVisible = true;
       }
     },
     

  }
}
</script>

<style scoped>
.customer-list-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 4px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-descriptions {
  margin-top: 20px;
}

/* 合同信息区域样式 */
.contract-info-section {
  margin-top: 30px;
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

.section-title {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.no-contract-info {
  margin-top: 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 0;
  border-top: 1px solid #e4e7ed;
}

/* 图片预览样式 */
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  max-height: 500px;
  overflow-y: auto;
}

.image-item {
  flex: 0 0 auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 图片加载状态样式 */
.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.image-slot i {
  font-size: 30px;
  margin-bottom: 10px;
}

.image-slot p {
  margin: 0;
  font-size: 14px;
}

.el-descriptions-item__label {
  font-weight: bold;
  background-color: #f5f7fa;
}
</style> 